<template>
  <view class="page">
    <!-- 地址 、搜索框 -->
    <block v-if="!hasLogin">
      <!-- 系统通知 所有评论 -->
      <view class="other-message">
        <view class="option-area-item" @click="goNotify">
          <view class="option-area-item-title">
            <image class="icon" src="/static/images/message/zhaohu@2x.png" />
            招呼
          </view>
          <view
            style="color: #9b9b9b; font-size: 26upx"
            class="icon iconfont iconright1"
          ></view>
          <view class="red_circle" v-if="greetCount != 0">{{
            greetCount
          }}</view>
          <view class="line" />
        </view>

        <view class="option-area-item" @click="goAsk">
          <view class="option-area-item-title">
            <image class="icon" src="/static/images/message/biaobai@2x.png" />
            表白
          </view>
          <view
            style="color: #9b9b9b; font-size: 26upx"
            class="icon iconfont iconright1"
          ></view>
          <view class="line" />
        </view>

        <view class="option-area-item" @click="goAdd">
          <view class="option-area-item-title">
            <image class="icon" src="/static/images/message/sousuo@2x.png" />
            查找或者添加好友
          </view>
          <view
            style="color: #9b9b9b; font-size: 26upx"
            class="icon iconfont iconright1"
          ></view>
          <view class="red_circle" v-if="commitNum != 0">{{ commitNum }}</view>
          <view class="line" />
        </view>
      </view>
      <view class="sepline"> </view>

      <block>
        <view v-if="conversationList.length === 0" class="invite-no-data">
          <image
            src="https://www.casita.net.cn/wx/img/wx/gkxcx/icon/wuyaoqing.png"
          ></image>
          <view class="no-data-text">暂无聊天对话记录</view>
        </view>
        <uni-swipe-action v-else>
          <uni-swipe-action-item
            v-for="(item, index) in conversationList"
            :key="index"
            :options="options"
            @click="actionClick(item)"
            @change="change"
          >
            <view class="chat-item" @click="goChat(item)">
              <image
                class="avatar"
                :src="item.userProfile.avatar"
                mode="aspectFill"
              />
              <view class="user-info">
                <view class="name-box">
                  <view class="name">{{ item.userProfile.nick }}</view>
                  <image
                    class="sex-icon"
                    :src="sexIcon(item.userProfile.gender)"
                    mode="aspectFit"
                  ></image>
                  <view
                    v-if="item.lastMessage.lastTime !== 'Invalid Date'"
                    class="time"
                  >
                    {{ item.lastMessage.lastTime }}
                  </view>
                </view>
                <view class="flex-row v-m5">
                  <view class="tag-age" v-if="item.userProfile.userinfo.age">
                    {{ item.userProfile.userinfo.age }}岁
                  </view>
                  <view
                    class="tag-minghua"
                    v-if="item.userProfile.userinfo.user_status"
                  >
                    {{ item.userProfile.userinfo.user_status }}
                  </view>
                  <view
                    class="tag-yuanfen"
                    v-if="item.userProfile.userinfo.fate_value"
                  >
                    缘分值{{ item.userProfile.userinfo.fate_value }}
                  </view>
                </view>
                <view style="height: 15px"></view>
                <!-- 相互关注  回关 -->
                <view class="flex-row flex-between">
                  <view class="font15">{{ lastMsg(item.lastMessage) }}</view>
                  <view class="un-read-num" v-if="item.unreadCount">
                    {{ item.unreadCount }}
                  </view>
                </view>
              </view>
              <view class="bot-line" />
            </view>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </block>
    </block>

    <block v-else>
      <view class="nodata">
        <image class="img" src="http://qnimage.xiteng.com/zky_wudenglu.png" />
        <view class="tip"> 您还没有登录，请登录后查看消息 </view>
        <view class="btn" @click="goLogin"> 登录 </view>
      </view>
    </block>
    <TabBar :current-page="1" />
  </view>
</template>

<script>
import { fullpath, REFRESH_CONVERSATIONS } from "@/util";

import { chat_time } from "@/util/time.js";
import { applyList } from "@/api/call/call.js";
import { mapState, mapMutations, mapActions, mapGetters } from "vuex";
import uniSwipeAction from "@/components/uni-swipe-action/uni-swipe-action.vue";
import uniSwipeActionItem from "@/components/uni-swipe-action-item/uni-swipe-action-item.vue";
export default {
  components: {
    uniSwipeAction,
    uniSwipeActionItem,
  },
  data() {
    return {
      options: [
        {
          text: "添加通讯录",
          style: {
            backgroundColor: "#2a7dfa",
          },
        },
      ],
      unReadNum: 1,
      histChatList: [],
      sysNum: "0",
      commitNum: "0",
      conversationList: [],
      beAppliedList: [],
    };
  },
  onLoad(options) {
    this.reqGreetList();
    uni.$on(REFRESH_CONVERSATIONS, () => {
      // 获取会话列表
      this.getConversationList();
    });
  },
  onUnload() {
    // 移除监听事件
    uni.$off(REFRESH_CONVERSATIONS);
  },
  onShow() {
    this.setUserInfo();
    //检测登录状态
    this.checkLogin();
    this.setUpIM(() => {
      this.loginIM();
    });
  },
  computed: {
    ...mapState({
      vuex_tabbar: (state) => state.tabbarStore.vuex_tabbar,
    }),
    ...mapState("userStore", ["userInfo", "hasLogin"]),
    ...mapState("chatStore", ["hasSysMessage"]),
    showTips() {
      return (item) =>
        item.imMessage.readStatus == 0 &&
        item.imMessage.fromId !== this.userInfo.userId;
    },
    greetCount() {
      const list = this.beAppliedList.filter(
        (greet) => greet.applyStatus === 0
      );
      return list.length;
    },
  },
  onReachBottom() {
    console.log("onReachBottom");
    this.getConversationListByServe(this.users);
  },
  methods: {
    ...mapMutations("tabbarStore", ["setUnReadCount"]),
    ...mapMutations("chatStore", ["setCurrentPerson", "setChatLogin"]),
    ...mapActions("chatStore", ["get_chat_contact_list"]),
     beforeSwitch(index) {
      console.log("home beforeSwitch====message=", index);
      if (index != 2) {
        return true;
      } else {
        uni.navigateTo({
          url: "/pageA/publish/publish",
        });
        return false;
      }
    },
    reqGreetList() {
      applyList().then((res) => {
        if (res.status == 1) {
          this.beAppliedList = res.data.beAppliedList;
        }
      });
    },
    getConversationList() {
      this.$im.getConversationList().then((ret) => {
        let conversationList = ret.data.conversationList;
        let count = 0;
        let users = [];
        this.conversationList = conversationList.map((v) => {
          count += v.unreadCount;
          v.realTime = v.lastMessage.lastTime * 1000;
          let lastTime = v.lastMessage.lastTime;
          v.lastMessage.lastTime =
            typeof lastTime == "string"
              ? lastTime
              : chat_time(v.lastMessage.lastTime * 1000);
          // chat_time(v.lastMessage.lastTime*1000)
          v.userProfile.user_id = this.handleUserId(v.userProfile.userID);
          users.push(v.userProfile.user_id);
          return v;
        });
        if (conversationList.length < 10) {
          console.log("conversationList.length");
          this.getConversationListByServe(users);
        }
        this.users = users;
        this.setUnReadCount(count);
      });
    },
    async loginIM() {
      this.$im.login();
    },
    handleUserId(userid) {
      return (
        userid.substr(0, 8) +
        "-" +
        userid.substr(8, 4) +
        "-" +
        userid.substr(12, 4) +
        "-" +
        userid.substr(16, 4) +
        "-" +
        userid.substr(20, 12)
      );
    },
    // 获取好友列表
    getConversationListByServe(users) {
      console.log("getConversationList");
      let params = {
        users,
      };
      this.$request
        .post({
          url: "chat/conversation-list",
          data: params,
        })
        .then(
          (info) => {
            console.log("infoinfoinfo", info);
            let users = [];
            let conversationList = [];
            for (let v of info.conversationList) {
              let lastMessage = v.lastMessage;
              let nextMsg = lastMessage.lastMessage || {
                MsgContent: { Text: "" },
                MsgType: "",
              };
              users.push(v.userProfile.userID);
              let lastTime = new Date(lastMessage.lastTime).getTime();
              v.realTime = lastTime;
              v.lastMessage = {
                lastTime: chat_time(lastTime),
                type: nextMsg.MsgType || "",
                payload: {
                  text: nextMsg.MsgContent.Text || "",
                },
              };
              v.userProfile.user_id = this.handleUserId(v.userProfile.userID);
              conversationList.push(v);
            }
            this.users = [...this.users, ...users];
            let conversationListArr = [
              ...this.conversationList,
              ...conversationList,
            ];
            conversationListArr.sort(function (a, b) {
              return b.realTime - a.realTime;
            });
            this.conversationList = conversationListArr;
            console.log("this.conversationList", this.conversationList);
          },
          (res) => {}
        );
    },

    lastMsg(item) {
      if (item.type == "TIMSoundElem") {
        return "[语音]";
      } else if (item.type == "TIMImageElem") {
        return "[图片]";
      } else if (item.type == "TIMTextElem") {
        if (
          item.payload.text.includes("gift--") ||
          item.payload.text.includes("giftto--")
        ) {
          return "[礼物]";
        } else {
          return item.payload.text;
        }
      }
    },
    sexIcon(sex) {
      if (sex == "0") {
        return require("@/static/images/message/nan_sign.png");
      } else {
        return require("@/static/images/message/nv_sign.png");
      }
    },
    setUpIM(cb) {
      this.$request
        .get({
          url: "chat/tencetIm/sig",
        })
        .then(
          (result) => {
            console.log("tencetIm info", result);
            if (result.status === 1) {
              const { tencent_im_sign } = result.data;
              uni.setStorageSync("tencent_im_sign", tencent_im_sign);
              cb && cb();
            }
          },
          (res) => {}
        );
    },

    // 获取好友列表
    getFirendList() {
      this.$request
        .get({
          url: "chat/friend/list",
        })
        .then(
          (info) => {
            this.histChatList = info.data;
            console.log("[][][]");
            console.log(info);
          },
          (res) => {}
        );
    },

    //删除第一位为逗号
    handleComma(val) {
      if (val && val.indexOf(",") === 0) {
        return val.substr(1);
      } else {
        return val;
      }
    },
    goSearch() {
      console.log(111);
      uni.navigateTo({
        url: "/pagesA/search/search",
      });
    },
    actionClick(item) {
      uni.navigateTo({
        url: "pageIM/pages/message/chat",
      });
      // console.log('item');
      // console.log(item)
      // this.savePhoneBookUser(item.userId);
    },
    change(open) {
      console.log("当前开启状态：" + open);
    },
    savePhoneBookUser(linkUserId) {
      const params = {
        linkUserId,
      };
      this.$request
        .post({
          url: "phonebook/save",
          data: params,
        })
        .then(
          (info) => {
            uni.showToast({
              title: info,
            });
            console.log("info", info);
          },
          (res) => {}
        );
    },

    setUserInfo() {
      var userInfo = uni.getStorageSync("userInfo");
      const params = {
        nick: userInfo.nick_name,
        gender:
          userInfo.gender == "M" ? "Gender_Type_Male" : "Gender_Type_Female",
        birthDay: userInfo.birthday,
        location: userInfo.native_place,
        selfSignature: userInfo.native_place,
        image: userInfo.avatar,
      };
      this.$request
        .post({
          url: "chat/tencetIm/setUserInfo",
          data: params,
        })
        .then(
          (info) => {
            console.log("info", info);
          },
          (res) => {}
        );
    },

    goAsk() {
      uni.requestSubscribeMessage({
        tmplIds: [
          "9Chs6d0cOuRoTO0R85M8AyXUuxtUMSCoyoCH8FSDzOI",
          "cclyr_09UZSZcYgadke6mpOvbvIQkBbbT7IU5ChH-d0",
        ],
        success(res) {},
      });
      uni.navigateTo({
        url: "/pageConfess/mineConfession/mineConfession",
      });
    },
    goAdd() {
      uni.navigateTo({
        url: "/pageIM/add_contact/add_contact",
      });
    },
    goContactList() {
      uni.navigateTo({
        url: "/pageIM/contact-list/contact-list",
      });
    },
    goNotify() {
      uni.navigateTo({
        url: "/pageA/call/index",
      });
    },
    goEnters(item) {
      uni.navigateTo({
        url: item.page,
      });
    },
    goLogin() {
      uni.navigateTo({
        url: "/pagesA/login/login",
      });
    },
    //获取未读信息
    getMsgMap() {
      this.$request
        .get({
          url: "sysMessage/getMsgMap",
        })
        .then(
          (info) => {
            console.log("info", info);
            for (let k of info) {
              if (k.label == "通知") {
                this.sysNum = k.value ? k.value : 0;
              }
              if (k.label == "评论") {
                this.commitNum = k.value ? k.value : 0;
              }
            }
          },
          (res) => {}
        );
    },

    checkLogin() {
      try {
        const userInfo = uni.getStorageSync("userInfo");
        if (userInfo) {
          // 获取历史联系人
          // this.get_chat_contact_list();

          //连接 聊天服务
          this.checkConnectWS();
          this.setChatLogin(true);
          this.setUserInfo(userInfo);

          // console.log('get_chat_contact_list',this.get_chat_contact_list())
        } else {
          this.setChatLogin(false);
        }
      } catch (e) {
        //TODO handle the exception
      }
    },
    checkConnectWS() {
      getApp().connectWS();
    },
    goChat(item) {
      console.log("goChat", item);
      var jsonData = {};
      jsonData.imgUrl = item.userProfile.avatar;
      jsonData.user_id = item.userProfile.userID;
      jsonData.user_id2 = item.userProfile.user_id;
      jsonData.username = item.userProfile.nick;
      uni.navigateTo({
        url: "/pageIM/HM-chat/HM-chat?data=" + JSON.stringify(jsonData),
      });
      // const chatLogin = getApp().globalData.chatLogin;
      // if (chatLogin) {

      // }
      // this.setCurrentPerson(item);
      // uni.navigateTo({
      // 	url: `/pagesA/chat-contactlist/chat?userId=${item.userId}`
      // })
    },
    imgPath(src) {
      return fullpath(src);
    },
    chatTime(time) {
      return chat_time(time);
    },
  },
};
</script>

<style scoped lang="less">
.page {
  width: 100%;
  min-height: 100vh;
  // background-color: #F5F6F9;
  background-color: #fff;

  .sepline {
    width: 100%;
    background-color: #f5f6f9;
    height: 16upx;
  }

  .invite-no-data {
    background-color: #fff;
    text-align: center;
    margin-top: 180upx;

    image {
      width: 210upx;
      height: 197upx;
      margin: 0 auto;
    }

    .no-data-text {
      font-size: 28upx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(72, 107, 157, 1);
      line-height: 30upx;
      text-align: center;
      padding-bottom: 116upx;
      margin-top: 14upx;
    }
  }

  .other-message {
    margin-bottom: 16upx;

    .option-area-item {
      height: 99upx;
      font-size: 26upx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(34, 34, 34, 1);
      display: flex;
      justify-content: space-between;
      align-items: center;
      // border-bottom: 1px solid #F2F2F2;
      padding: 0upx 32upx;
      background-color: #fff;

      position: relative;

      .line {
        position: absolute;
        background-color: #f2f2f2;
        height: 2upx;
        bottom: 0;
        left: 80upx;
        right: 30upx;
      }

      .option-area-item-title {
        display: flex;
        align-items: center;
        margin-left: 15upx;
        position: relative;

        .icon {
          width: 42upx;
          height: 42upx;
          object-fit: contain;
          margin-right: 42upx;
        }
      }

      .red_circle {
        position: absolute;
        top: 30upx;
        right: 76upx;
        width: 40upx;
        height: 40upx;
        -webkit-border-radius: 50%;
        border-radius: 50%;
        background-color: #fe596a;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .more_quan {
        font-size: 26upx;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: rgba(255, 255, 255, 1);
      }

      .more_quan > .icon {
        vertical-align: middle;
      }
    }
  }

  .search-box-wrapper {
    display: flex;
    flex-direction: row;
    align-items: center;
    background-color: #ffffff;

    .input-box {
      display: flex;
      flex-direction: row;
      align-items: center;
      flex: 1;
      border-radius: 8upx;
      box-sizing: border-box;
      background-color: #f5f5f5;
      position: relative;
      margin-bottom: 22upx;
      overflow: hidden;
      margin: 20upx 32upx;
      padding: 0 20upx;
      box-sizing: border-box;

      .uni-input {
        font-size: 28upx;
        background-color: #f5f5f5;
        color: #a3a3a3;
        height: 75upx;
      }

      .search-icon {
        width: 32upx;
        height: 32upx;
      }
    }
  }

  .quick-enters {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 31px 15px 23px 15px;
    margin: 0 10px;
    border-bottom: 1px solid #f9f9f9;

    .quick-item {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .quick-item-desc {
      margin-top: 16upx;
      font-size: 24upx;
      color: #cccccc;
    }

    .quick-item-title {
      margin-top: 20upx;
      font-size: 28upx;
      color: rgba(51, 51, 51, 1);
      font-weight: 700;
    }

    .quick-item-image {
      width: 98upx;
      height: 98upx;
    }
  }

  .nodata {
    display: flex;
    min-height: 100vh;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .tip {
      color: #666666;
      font-size: 26upx;
      margin: 30upx 0;
    }

    .img {
      object-fit: contain;
      height: 288upx;
      width: 374upx;
    }

    .btn {
      width: 145upx;
      height: 69upx;
      background: rgba(42, 125, 250, 1);
      border-radius: 4upx;
      text-align: center;
      line-height: 69upx;
      color: #fff;
    }
  }
}

.chat-item {
  width: 100%;
  height: 194upx;
  display: flex;
  flex-direction: row;
  align-items: center;
  background-color: #ffffff;
  padding: 0 30upx;
  box-sizing: border-box;

  position: relative;

  .time {
    // position: absolute;
    // top: 22upx;
    // right: 20upx;
    flex: 1;
    text-align: right;
    font-size: 24upx;
    font-weight: 400;
    color: rgba(135, 139, 153, 1);
  }

  .red_circle {
    position: absolute;
    top: 80upx;
    right: 20upx;
    width: 20upx;
    height: 20upx;
    border-radius: 50%;
    background-color: #fe596a;
  }
}

.user-info {
  flex: 1;

  .name-box {
    display: flex;
    flex-direction: row;
    align-items: center;

    .sex-icon {
      width: 42rpx;
      height: 21px;
      object-fit: contain;
    }

    .name {
      font-size: 30upx;
      color: #444444;
      font-weight: bold;

      word-break: break-word; //换行模式
      overflow: hidden;
      text-overflow: ellipsis; //修剪文字
      display: -webkit-box;
      -webkit-line-clamp: 1; //此处为上限行数
      -webkit-box-orient: vertical;
      max-width: 50%;
    }
  }
}

.bot-line {
  position: absolute;
  bottom: 0;
  height: 2upx;
  background-color: #f5f5f5;
  left: 124upx;
  right: 0upx;
}

.content {
  display: flex;
  justify-content: space-between;

  .content-text {
    font-size: 26upx;
    color: #888787;
    word-break: break-word; //换行模式
    overflow: hidden;
    text-overflow: ellipsis; //修剪文字
    display: -webkit-box;
    -webkit-line-clamp: 1; //此处为上限行数
    -webkit-box-orient: vertical;
    width: 500upx;
  }
}

.avatar {
  width: 84upx;
  height: 84upx;
  border-radius: 50%;
  background-color: #f9f9f9;
  margin-right: 20upx;
}
</style>
